<?php
class CategorySaveEditAction extends AdminAction
{
	public function __construct()
	{
		parent::__construct();
		$this->responseType = 'json';
	}
	
	protected function afterConstruct()
	{
		$this->parseDtds('category','edit');
	}
	
	public function execute()
	{
		$id		= $this->context->post('id');
		$data	= $this->getValidData();
		
		$categoryService = new CategoryService();
		
		//检查上级类目和当前类目ID的关系
		if(!$categoryService->checkIdAndPid($id, $data['pid']))
		{
			$this->data['error_messages']['pid']	= array('error'=>'上级栏目不能是当前栏目或者它的子栏目');
		}
		
		//最多只支持三级栏目
		if(!$categoryService->checkPidLevel($data['pid']))
		{
			$this->data['error_messages']['pid']	= array('error'=>'最多只能添加三级栏目');
		}
		
		//标签
		$data['tags'] = str_replace("，", ",", $data['tags']);
		$tmp = explode(',', $data['tags']);
		if(count($tmp)>3)
		{
			$this->data['error_messages']['tags']	= array('error'=>'最多只能添加三个栏目标签');
		}
		
		if(empty($this->data['error_messages']))
		{
			if(is_numeric($id) && $id>0)
			{
				$categoryService->update($id,$data);
				$this->code	= 200;
			}
			else
			{
				$id	= $categoryService->add($data);
				if($id)
				{
					$this->code	= 200;
				}
				else
				{
					$this->code	= 400;
				}
			}
		}
		else
		{
			$this->code	= 400;
		}
		
		$this->data['forward'] = C('LtUrl')->generate('Category', 'Index',array('pid'=>$data['pid']));
	}
}
